import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/my/my_purchase_logic.dart';
import 'package:sports_new/entity/ai/ai_combo_entity.dart';
import 'package:sports_new/entity/ai/ai_item_entity.dart';
import 'package:sports_new/entity/my/order_list_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/king/items/history_label.dart';
import 'package:sports_new/view/pick/ai/ai_type.dart';
import 'package:sports_new/view/pick/items/ai_combo_item.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';

import '../../../resources/styles.dart';
import '../../../utils/routes.dart';
import '../../../utils/toast_utils.dart';
import '../../../utils/utils.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/base/qkd_dialog.dart';
import '../../pick/items/ai_match_item.dart';
import '../../pick/items/ai_plan_item.dart';

class PurchaseItem extends StatefulWidget {
  const PurchaseItem({
    super.key,
    required this.data,
    required this.type});

  final OrderListEntity data;
  final PurchaseType type;

  @override
  State<PurchaseItem> createState() => _PurchaseItemState();
}

class _PurchaseItemState extends State<PurchaseItem> {
  OrderListEntity get data => widget.data;
  PurchaseType get type => widget.type;
  bool showAll = false;
  
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 10, top: 10, right: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: Colours.white,
      ),
      child: Column(
        children: [
        _itemInfo(),
        if(type == PurchaseType.planForm)
          _planFormInfo(data),
        const Divider(
          height: 0.5, color: Colours.greyEE,
        ).paddingSymmetric(horizontal: 10),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            if(type == PurchaseType.plan) {
              Utils.onEvent('wd_wdyg_djgd');
              Get.toNamed(Routes.expertViewpoint, arguments: data.planId);
            }
          },
          child: DefaultTextStyle(
            style: const TextStyle(fontSize: 12),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if(type == PurchaseType.plan) _planMatchInfo(data),
                  if(type == PurchaseType.ai && data.aiInfo != null)...[
                    _aiInfo(),
                    const Divider(height: 0.5,color: Colours.greyEE)
                  ],
                  if(type == PurchaseType.couponPack)...[
                    _couponPackInfo(),
                    const Divider(height: 0.5,color: Colours.greyEE)
                  ],
                  Container(height: 10),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if(data.couponInfo1 != null && data.couponInfo2 != null)
                            _discountInfo().paddingOnly(bottom: 4),
                            _time().paddingOnly(bottom: 4),
                            _orderInfo().paddingOnly(bottom: type == PurchaseType.subs?16:4),
                            if(type == PurchaseType.planForm) Container(height: 6),
                            if(type == PurchaseType.plan)
                            _planRight().paddingOnly(bottom: 16),
                            if(type != PurchaseType.plan && type != PurchaseType.planForm)
                            _featurePrice().paddingOnly(bottom: 10,top: 2)
                          ],
                        ),
                      ),
                      if(type == PurchaseType.plan || type == PurchaseType.planForm)
                      _planPrice().paddingOnly(bottom: 16),
                      if(type != PurchaseType.plan && type != PurchaseType.planForm)
                      _featureButton().paddingOnly(bottom: 10,top: 2)
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ]),
    );
  }

  Widget _itemInfo(){
    List<String> state = [
      if(type == PurchaseType.planForm)...["已完成"]else...[""],
      "已完成",
      "已退款"
    ];
    return SizedBox(
      height: 52,
      child: Padding(
        padding: EdgeInsets.only(left: type == 1?0:10,right: 10),
        child: Row(
          children: [
            GestureDetector(
              onTap: () {
                switch(type){
                  case PurchaseType.plan:case PurchaseType.planForm:
                    Get.toNamed(Routes.userPage,
                      arguments: data.tagId, parameters: {'type': '2'});
                    break;
                  case PurchaseType.ai:
                    Get.toNamed(
                      AiType.getTypeByPayId(data.tagId.toInt() ?? 0)?.route ?? ""
                    );
                    break;
                  case PurchaseType.vip:
                    Get.toNamed(Routes.vipCenter);
                    break;
                  case PurchaseType.secret:
                    Get.toNamed(Routes.secretList);
                    break;
                  case PurchaseType.subs:
                    Get.toNamed(Routes.subscribe);
                    break;
                  case PurchaseType.couponPack:
                    Get.toNamed(Routes.saleCenter,arguments: PurchaseType.couponPack.name);
                    break;
                }
              },
              child: Row(
                children: [
                Container(
                  clipBehavior: Clip.antiAlias,
                  decoration: BoxDecoration(
                    shape: type == PurchaseType.ai?BoxShape.rectangle:BoxShape.circle
                  ),
                  child: CachedNetworkImage(
                    imageUrl: data.tagLogo ?? '',
                    width: 32,
                    height: 32,
                    fit: BoxFit.cover,
                  )
                ),
                const SizedBox(width: 10),
                QkdText(data.tagName ?? '', fontSize: 15),
                if(type == PurchaseType.planForm && data.issue.hasValue)
                QkdText("[${data.issue ?? 0}期]",
                  color: Colours.blue39407E,fontSize: 15
                ).paddingOnly(left: 4),
                const SizedBox(width: 6),
                Image.asset(
                  Utils.getImgPath('arrow_right.png'),
                  width: 6,
                  height: 10,
                )
              ]),
            ),
            const Spacer(),
            QkdText(state[data.status ?? 0],fontSize: 12)
          ]
        ),
      )
    );
  }

  Widget _planFormInfo(OrderListEntity data){
    return GestureDetector(
      onTap: () => Get.toNamed(Routes.planFormDetail,arguments: data.issueId),
      child: Column(
        children: [
          ...data.stageList?.reversed.map(
                  (e) => _planFormItem(e)
          ).toList().insertEvery(
            Container(height: 8)).sublist(0,showAll?null:1
          ) ?? [],
          if((data.stageList?.length ?? 0) > 1)
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => setState(() {
              showAll = !showAll;
            }),
            child: Container(
              width: Get.width,
              padding: const EdgeInsets.symmetric(vertical: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  QkdText(showAll?"收起":"全部", fontSize: 12,color: Colours.grey99),
                  Container(width: 2),
                  Image.asset(width: 12,
                    Utils.getImgPath(showAll?"arrow_up.png":"arrow_down.png")
                  )
                ],
              ),
            ),
          )
        ]
      ).paddingSymmetric(horizontal: 8),
    );
  }
  
  Widget _aiInfo(){
    AiType? type = AiType.getTypeByPayId(data.aiInfo?.aiPayId?? 0);
    var info = data.aiInfo?.info;
    return DefaultTextStyle(
      style: const TextStyle(
        fontSize: 15,
        color: Colours.text,
        fontWeight: FontWeight.w500
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          if(type == AiType.combo)...[
            const QkdText("解锁选项："),
            ...info?.items?.map((e) => aiLine(e)) ?? []
          ]else...[
            aiLine(info as AiItemEntity?)
          ],
          if(type == AiType.plan)
          AiPlanItem.planCount(info as AiItemEntity?)
        ].insertEvery(Container(height: 6))
      ).paddingSymmetric(vertical: 10),
    );
  }

  Widget _couponPackInfo(){
    var info = data.couponPackInfo;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          QkdText("券包名称：${info?.packageName??" "}",
            fontSize: 15,fontWeight: FontWeight.w500,color: Colours.text
          ),
          if(info?.endTime.hasValue??false)
          QkdText("到期时间：${DateTime.parse(info!.endTime!).formatedString("yyyy-MM-dd")}",
            color: Colours.text
          ).paddingOnly(top: 2),
        ],
      ),
    );
  }

  Widget aiLine(AiItemEntity? item){
    List<String> text = [];
    item?.aiOption?.forEach((element) {
      if(element.option.hasValue && element.odds.hasValue) {
        text.add("${element.option} ${element.odds?.split("指数").join("")}");
      }
    });
    String matchInfo = [
      item?.homeName ?? "",
      if(item?.homeScore90 != null && item?.guestScore90 != null)...[
        "${item?.homeScore90}:${item?.guestScore90}"
      ]else...[
        "vs"
      ],
      item?.guestName ?? ""
    ].join(" ");
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        QkdText(matchInfo),
        Container(height: 2),
        Row(
          children: [
            QkdText("选项建议："),
            ...List<Widget>.generate(text.length,
              (index) => QkdText(text[index],
                color: item?.aiOption?[index].hit == true?Colours.main:null
              )
            ).insertEvery(Container(width: 6))
          ]
        ),
      ],
    );
  }
  
  Widget _planFormItem(StageList data){
    return DefaultTextStyle(
      style: const TextStyle(color: Colours.text,fontSize: 15),
      child: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colours.greyF2F3F7,
          borderRadius: BorderRadius.circular(4)
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            QkdText("阶段${data.stage.toChn}",
              fontWeight: FontWeight.w500
            ),
            ...data.matchList?.map(
              (e) => Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  QkdText(e.matchInfo ?? ""),
                  ...e.playInfoList!.map(
                    (info) => Row(
                      children: [
                        QkdText(
                          "[${e.playTypeName ?? ""}]",
                          needCenter: true,
                          color: Color(0xFF39407E)
                        ),
                        const SizedBox(width: 4),
                        QkdText(
                          '${info.code}：${info.name}  ',
                          color: info.win == 1 ? Colours.main : Colours.text,
                          needCenter: true,
                        )
                      ],
                    ),
                  )
                ],
              )
            ).toList() ?? []
          ].insertEvery(Container(height: 8)),
        )
      ),
    );
  }

  Widget _planMatchInfo(OrderListEntity data) {
    return Stack(
      children: [
        Column(
          children: data.matchList?.map((e) => oneMatch(e)).toList() ?? [],
        ),
        if(type == PurchaseType.plan)
        Positioned(
          top: 10,right: 0,
          child: HistoryLabel.viewpoint(
            width: 36,
            state: int.parse(data.planStatus!)
          ),
        )
      ],
    );
  }

  Widget oneMatch(MatchList e) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 10),
        QkdText(
          e.matchInfo ?? '',
          fontSize: 15,
          fontWeight: FontWeight.w500,
          color: Colours.text,
        ),
        const SizedBox(height: 5),
        ...e.playInfoList!.map(
              (info) => Row(
            children: [
              QkdText(
                "[${e.playTypeName ?? ""}]",
                fontSize: 15, color: const Color(0xFF39407E),
                needCenter: true,
              ),
              const SizedBox(
                width: 4,
              ),
              QkdText(
                '${info.code}：${info.name}  ',
                color: info.win == 1 ? Colours.main : Colours.text,
                needCenter: true,
              )
            ],
          ),
        ),
        const SizedBox(height: 10),
        Container(
          width: double.infinity,
          height: 0.5,
          color: Colours.greyEE,
        )
      ],
    );
  }

  Widget _discountInfo(){
    return Row(
      children: [
        QkdText(
          '${data.couponInfo1}',color: Colours.grey99,
        ),
        QkdText(
          '${data.couponInfo2}',color: Colours.main
        )
      ],
    );
  }

  Widget _time(){
    return QkdText(
      '下单时间 ${data.createTime}',color: Colours.grey99,
    );
  }

  Widget _orderInfo(){
    return Row(
      children: [
        Flexible(
          child: QkdText(
            '订单编号 ${data.id}'.split("").join(),
            maxLines: 2,
            color: Colours.grey99
          ),
        ),
        const SizedBox(width: 2),
        GestureDetector(
          onTap: () {
            Clipboard.setData(ClipboardData(text: data.id ?? ''));
            ToastUtils.show("已复制订单编号");
          },
          child: Image.asset(
              Utils.getImgPath('copy.png'),
              width: 12, height: 12
          ),
        ),
      ],
    );
  }

  Widget _planRight(){
    return Row(
      children: [
        if(data.activityId == 1 || data.activityId == 2)
          _activityLabel(
              text: "本单享受${data.activityId == 1 ? "首购不中退款" : "粉丝不中退款"}",
              title: "${data.activityId == 1?"首购":"粉丝"}不中退说明",
              content: [
                if(data.activityId == 1)
                  "1.首次购买该专家的方案且选项不中，即可享受不中退活动。",
                if(data.activityId == 2)
                  "1. 购买方案前关注专家，即可享受不中退活动。",
                "2. 建议选项中的首选和次选均不中，则为不中。",
                "3. 比赛赛果确认后的半小时内，实付球币金额自动退款至球币余额内。"
              ].join("\n")
          ),
        if(data.activityId == 3)
          _activityLabel(
              text: "本单享受“会员免费看”权益",
              content: "会员每天可免费解锁1篇专家方案",
              title: "会员免费解锁方案"),
      ],
    );
  }

  Widget _planPrice(){
    return QkdText(
      '实付${data.gold!.toStringAsFixed(2)}球币',
      fontSize: 12,
      fontWeight: FontWeight.w500,
    );
  }

  Widget _featurePrice(){
    return DefaultTextStyle(
      style: const TextStyle(
        fontSize: 12,
        color: Colours.text,
        fontWeight: FontWeight.w500
      ),
      child: Row(
        children: [
          if(type != PurchaseType.couponPack)...[
            QkdText(data.days == "0天"?"单条解锁":"${data.days ?? ""}套餐"),
            Container(width: 4)
          ],
          QkdText("实付${data.gold}球币".changeUnit),
        ]
      ),
    );
  }

  Widget _featureButton(){
    return QkdButton(
      onPressed: (){
        switch(type){
          case PurchaseType.ai:
            Utils.onEvent("order_model_renew");
            Get.toNamed(Routes.aiPay,arguments: AiType.getTypeByPayId(data.tagId.toInt()??0));
            break;
          case PurchaseType.vip:
            Get.toNamed(Routes.vipCenter);
            break;
          case PurchaseType.secret:
            Get.toNamed(Routes.secretPay);
            break;
          case PurchaseType.subs:
            Get.toNamed(Routes.subsPay,arguments: data.tagId);
            break;
          case PurchaseType.couponPack:
            Get.toNamed(Routes.saleCenter,arguments: PurchaseType.couponPack.name);
            break;
          default:
            null;
        }
      },
      text: type == PurchaseType.couponPack?"再次购买":"立即续费",
      height: 24,width: 72,
      borderRadius: 4,
      strutStyle: Styles.centerStyle(fontSize: 15),
      textStyle: const TextStyle(fontSize: 13),
      foregroundColor: Colours.white,
      backgroundColor: Colours.main,
    );
  }

  Widget _activityLabel({String? text, String? content,String? title}){
    return Padding(
      padding: const EdgeInsets.only(top: 4),
      child: Row(
        children: [
          QkdText(
            text ?? "",
            needCenter: true,
            color: Colours.grey99,
            fontSize: 12,
          ),
          Container(width: 4),
          Image.asset(width: 12, height: 12,
              color: Colours.grey99,
              Utils.getImgPath("question_mark.png")
          )
        ],
      ),
    ).tap(() => Get.dialog(QkdDialog.singleBUTTON(
        title ?? "",
        content: content,
        confirmText: "知道了")));
  }
}
